package com.start.autumn.config;

import de.codecentric.boot.admin.server.domain.entities.Instance;
import de.codecentric.boot.admin.server.domain.entities.InstanceRepository;
import de.codecentric.boot.admin.server.domain.events.InstanceEvent;
import de.codecentric.boot.admin.server.domain.events.InstanceStatusChangedEvent;
import de.codecentric.boot.admin.server.domain.values.StatusInfo;
import de.codecentric.boot.admin.server.notify.AbstractEventNotifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.Map;

@Component
public class CustomNotifier extends AbstractEventNotifier {
    private static final Logger LOGGER = LoggerFactory.getLogger(CustomNotifier.class);

    protected CustomNotifier(InstanceRepository repository) {
        super(repository);
    }

    /**
     * 这里可以处理服务下线和上线的业务处理，例如通知等等
     * @param event
     * @param instance
     * @return
     */
    @Override
    protected Mono<Void> doNotify(InstanceEvent event, Instance instance) {
        return Mono.fromRunnable(() -> {
            if (event instanceof InstanceStatusChangedEvent) {
                InstanceStatusChangedEvent statusChangedEvent = (InstanceStatusChangedEvent) event;
                StatusInfo statusInfo = statusChangedEvent.getStatusInfo();
                if (statusInfo.isUp()) {
                    LOGGER.info("服务恢复正常：{} ({})", instance.getRegistration().getName(),statusInfo.getStatus());
                } else if (statusInfo.isDown()) {
                    LOGGER.warn("服务健康检查失败（DOWN）：{} ({})", instance.getRegistration().getName(),statusInfo.getStatus());
                } else if (statusInfo.isOffline()) {
                    LOGGER.error("服务离线（OFFLINE）：{} ({})", instance.getRegistration().getName(), statusInfo.getStatus());
                } else {
                    LOGGER.info("服务状态变化：{} ({}) 状态为：{}", instance.getRegistration().getName(), event.getInstance(), statusInfo.getStatus());
                }
                Map<String, Object> details = statusInfo.getDetails();
                LOGGER.info("其他信息:{}",details);
            }
        });
    }

    @Override
    protected boolean shouldNotify(InstanceEvent event, Instance instance) {
        if (event instanceof InstanceStatusChangedEvent) {
            InstanceStatusChangedEvent statusChangeEvent = (InstanceStatusChangedEvent) event;
            String status = statusChangeEvent.getStatusInfo().getStatus();
            LOGGER.info("Status change event received: {}", event);
            return true;
        }
        return false;
    }
}
